//
// Created by 先通明 on 2018/8/24.
//
#include <stdlib.h>
#include <stdio.h>
#include "booth.h"


bool newcustomer(double x) {
    if (rand() * x / RAND_MAX < 1)
        return true;
    else
        return false;
}

// when is the time at which the customer arrives
// function returns an Item structure with the arrival time
// set to when and the processing time set to a random value
// in the range 1 - 3
Item customertime(long when) {
    Item cust;

    cust.processtime = rand() % 3 + 1;
    cust.arrive = when;

    return cust;
}

void intilizeBooth(Booth *booth, int hours, int perhour) {
    booth->hours = hours;
    booth->perhour = perhour;
    booth->min_per_cust = booth->hours / booth->perhour;
    booth->customers=0;
    booth->line_wait=0;
    booth->sum_line=0;
    booth->turnaways=0;
    booth->served=0;
}

void start_booth(Booth *booth) {
    srand(time(0));
    Queue line;
    InitializeQueue(&line);
    int cycle, cycleLimit;// 一分钟循环一次
    int wait_time = 0;//还要等待多长时间接待下一个顾客
    Item temp;
    cycleLimit = booth->hours * 60;
    for (cycle = 0; cycle < cycleLimit; ++cycle) {
        if (newcustomer(booth->min_per_cust)) {
            if (QueueIsFull(&line)) {
                booth->turnaways++;
            } else {
                booth->customers++;
                EnQueue(customertime(cycle), &line);
            }
        }
        if (wait_time <= 0 && !QueueIsEmpty(&line)) {
            DeQueue(&temp, &line);
            wait_time = temp.processtime;
            booth->line_wait += cycle - temp.arrive;
            booth->served++;//服务的顾客数+1
        }
        if (wait_time > 0) {
            wait_time--;
        }
        booth->sum_line += QueueItemCount(&line);
    }
    EmptyTheQueue(&line);
}

void show_booth(Booth *booth) {
    if (booth->customers > 0) {
        printf("customers accepted: %ld\n", booth->customers);
        printf("  customers served: %ld\n", booth->served);
        printf("       turnaways: %ld\n", booth->turnaways);
        printf("average queue size: %.2f\n",
               (double) booth->sum_line / (booth->hours * 60));
        printf(" average wait time: %.2f minutes\n",
               (double) booth->line_wait / booth->served);
    } else
        puts("No customers!");
}

